<?php
require_once "Zend/Tokenizer/Interface.php";
require_once "Zend/Socket.php";
require_once "Zend/Socket/Tcp/Connection/Interface.php";

abstract class Zend_Socket_Tcp_Connection_Abstract implements Zend_Socket_Tcp_Connection_Interface
{
	/**
	 * @var Zend_Tokenizer_Interface
	 */
	private $_tokenizer;

	/**
	 * @var Zend_Socket_Tcp_Server
	 */
	private $_server = null;

	/**
	 * Creates a client from a socket.
	 *
	 * @param Zend_Tokenizer_Interface $tokenizer
	 * @throws Zend_Socket_Exception
	 */
	public function __construct(Zend_Tokenizer_Interface $socketTokenizer)
	{
		if (!($socketTokenizer->getProducer() instanceof Zend_Socket)) {
			require_once "Zend/Socket/Exception";
			throw new Zend_Socket_Exception(
				"Cannot set PROT_READ or PROT_WRITE on a socket with PROT_LISTEN",
				$this
			);
		}
		$this->_tokenizer = $socketTokenizer;
	}

	/**
	 * Closes the socket if it has not been closed before.
	 */
	public function __destruct()
	{
		if ($this->Socket()->getState() != Zend_Socket::STATE_CLOSED) {
			$this->Socket()->close();
		}
	}

	/**
	 * Callback to be called when the client is registered in the select.
	 *
	 * @return void
	 */
	public function onRegister(Zend_Socket_Tcp_Server $server)
	{
		$this->_server = $server;
	}

	/**
	 * Closes the socket if it has not been closed before.
	 *
	 * @return void
	 */
	public function onUnregister()
	{
		if (!$this->Socket()->getState() != Zend_Socket::STATE_CLOSED) {
			$this->Socket()->close();
		}
		$this->_server = false;
	}

	/**
	 * Get the Client tokenizer.
	 * Can be the socket
	 *
	 * @return Zend_Tokenizer_Interface
	 */
	public function Tokenizer()
	{
		return $this->_tokenizer;
	}

	/**
	 * Get the socket.
	 *
	 * @return Zend_Socket
	 */
	public function Socket()
	{
		return $this->_tokenizer->getProducer();
	}

	/**
	 * Get the server.
	 *
	 * @return Zend_Socket_Tcp_Server
	 */
	public function Server()
	{
		return $this->_server;
	}
}
